/*
 * @author : TF-BJ-C064
 * @creation : 2014-8-6 下午9:42:02
 * @description : 
 *
 */

package com.umeng;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class UMStat {
	public Logger log = Logger.getLogger(UMStat.class);

	public static String TEST_URL = "http://www.umeng.com/apps/6ea3006b06b042652499f935/reports/load_table_data?page=1&per_page=30&start_date=2014-01-08&end_date=2014-08-06&versions[]=&channels[]=&segments[]=&time_unit=daily&stats=active_users";
	public static String APPS_URL = "http://www.umeng.com/apps";

	private Integer page;

	private List<App> applist = new ArrayList<App>();

	//http://www.umeng.com/apps/6ea3006b06b042652499f935/reports/load_table_data?
	//page=1&per_page=300&start_date=2014-01-08&end_date=2014-08-06&versions[]=&channels[]=&segments[]=&time_unit=daily&stats=active_users

	private UMUser user;

	String html;
	HttpClient httpclient = new DefaultHttpClient();
	Header[] cookieHeaders;
	HttpGet get = null;
	HttpPost post = null;
	HttpResponse httpResponse;


	public boolean apps() throws ParseException, IOException{
		httpclient.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
		get = new HttpGet(APPS_URL);
		get.setHeader("Cookie", user.getCookies());
		httpResponse = httpclient.execute(get);
		cookieHeaders = httpResponse.getHeaders("Set-Cookie");
		user.setCookie(cookieHeaders);
		html = EntityUtils.toString(httpResponse.getEntity());
		cookieHeaders = httpResponse.getHeaders("Set-Cookie");
		user.setCookie(cookieHeaders);
		get.releaseConnection();

		Document htmljsoup = Jsoup.parse(html);
		Elements ems = htmljsoup.select("ul.select-list li");
		if(ems!=null && ems.size()>0){
			for(Element appli : ems){
				App app = new App(appli.attr("app_id"), appli.text()); 
				if(app.getAppid()!=null && !app.getAppid().trim().isEmpty()){
					applist.add(app);
					log.info(app.toString());
				}
			}
		}else{
			log.info(html);
		}

		return true;
	}

	/**
	 * 统计活跃量
	 * <p>Title: statActive</p>
	 * <p>Description: </p>
	 * @param startdate e.g: 2014-01-08
	 * @param enddate   e.g: 2014-08-06
	 * @return json data
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public  JSONObject statActive(String startdate, String enddate, App app) throws ClientProtocolException, IOException{
		//http://www.umeng.com/apps/6ea3006b06b042652499f935/reports/load_table_data?
		//page=1&per_page=30&start_date=2014-01-08&end_date=2014-08-06&versions[]=&channels[]=&segments[]=&time_unit=daily&stats=active_users
		
		String url = "";
		url = "http://www.umeng.com/apps/"+ app.getAppid() +"/reports/load_table_data?";
		url += "page=1&per_page=1000&start_date="+startdate+"&end_date="+enddate+"&versions[]=&channels[]=&segments[]=&time_unit=daily&stats=active_users";

		log.info("statActive url="+url);
		
		httpclient.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
		get = new HttpGet( url );
		get.setHeader("Cookie", user.getCookies());
		httpResponse = httpclient.execute(get);
		cookieHeaders = httpResponse.getHeaders("Set-Cookie");
		user.setCookie(cookieHeaders);
		String jsontext = EntityUtils.toString(httpResponse.getEntity());
		get.releaseConnection();

		if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
			JSONObject json = JSONObject.fromObject(jsontext);
			return json;
		}
		return null;
	}


	//统计活跃量
	public  boolean statActive() throws ClientProtocolException, IOException{

		String url = "";
		//http://www.umeng.com/apps/6ea3006b06b042652499f935/reports/load_table_data?
		//page=1&per_page=30&start_date=2014-01-08&end_date=2014-08-06&versions[]=&channels[]=&segments[]=&time_unit=daily&stats=active_users
		for(App app : applist){
			url = "http://www.umeng.com/apps/"+app.getAppid()+"/reports/load_table_data?";
			url += "page=1&per_page=1000&start_date=2014-01-08&end_date=2014-08-06&versions[]=&channels[]=&segments[]=&time_unit=daily&stats=active_users";

			httpclient.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
			get = new HttpGet( url );
			get.setHeader("Cookie", user.getCookies());
			httpResponse = httpclient.execute(get);
			cookieHeaders = httpResponse.getHeaders("Set-Cookie");
			user.setCookie(cookieHeaders);
			html = EntityUtils.toString(httpResponse.getEntity());
			get.releaseConnection();
			log.info(html);
			try{
				JSONObject json = JSONObject.fromObject(html);
				if(json!=null){
					String result = (String)json.get("result");
					if(result!=null && result.equals("success")){
						JSONArray array = json.getJSONArray("stats");
						if(array!=null){
							for(int j=0; j<array.size(); j++){
								JSONObject jsonstat = (JSONObject) array.get(j);
								if(jsonstat!=null){
									AppStat appstat = new AppStat();
									appstat.setActive_sum((Integer)jsonstat.get("data"));
									if(appstat.parseDatetime((String)jsonstat.get("date")))
										app.getAppStatList().add(appstat);
								}
							}
						}
					}
					Integer total = (Integer )json.get("total");
				}
			}catch(Exception e){
				e.printStackTrace();
				return false;
			}

		}

		return true;
	}

	public boolean Save2Datebase() throws SQLException{
		//		KDataSource kds = new KDataSource();
		//		Connection conn = kds.getConnection();
		//		if(conn==null){
		//			log.error("conn==null");
		//			return false;
		//		}
		//		Statement statement = (Statement) conn.createStatement();
		//		String sql;
		//		int lines = 0;
		//
		//		for(App app : applist){
		//			sql = "insert into stat_active(uappid, appname, datetime, active_sum) values ";
		//			int sum = 0;
		//			for(AppStat appstat : app.getAppStatList()){
		//				if(sum>0)
		//					sql += ",";
		//				sql += "('"+app.getAppid()+"', '"+app.getAppname()+"','" +appstat.getDatetime() +"',"+appstat.getActive_sum() + ")";
		//				sum++;
		//			}
		//			lines = statement.executeUpdate(sql);
		//			System.out.println("lines="+lines);
		//		}
		return true;
	}

	public boolean test() throws ParseException, IOException{
		httpclient.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
		get = new HttpGet(TEST_URL);
		get.setHeader("Cookie", user.getCookies());
		httpResponse = httpclient.execute(get);
		cookieHeaders = httpResponse.getHeaders("Set-Cookie");
		user.setCookie(cookieHeaders);
		html = EntityUtils.toString(httpResponse.getEntity());
		get.releaseConnection();

		log.info(html);

		return true;
	}

	public UMUser getUser() {
		return user;
	}

	public void setUser(UMUser user) {
		this.user = user;
	}

	public List<App> getApplist() {
		return applist;
	}

	public void setApplist(List<App> applist) {
		this.applist = applist;
	}

}
